import sys
import os
import amara
from brightcontent.core.store import COMMON_PREFIXES, ATOM10_NS
from brightcontent.util import fixup_namespaces, quick_xml_scan, get_clean_title

def id_to_fname(id_):
    return '-'.join(id_.split('/')[-4:])
    #return id.replace(os.path.sep, '-')

def make_entry_filename(e):
    date = amara.binderytools.parse_isodate(str(e.published))
    title = get_clean_title(str(e.title))
    fn = "%s-%s.xml" % (date.strftime('%Y-%m-%dT%H-%M-%SZ'), title)
    return fn

input_file_or_url = sys.argv[1]
try:
    output_dir = sys.argv[2]
except IndexError:
    output_dir = '/tmp/atomstore'

try:
    os.makedirs(output_dir)
except OSError:
    pass

doc = amara.parse(input_file_or_url, prefixes=COMMON_PREFIXES)
envelope = amara.create_document(u"atom:feed", ns=ATOM10_NS)
for nonentry in doc.feed.xml_xpath(u'*[not(self::atom:entry)]'):
    envelope.feed.xml_append(nonentry)
f = open(os.path.join(output_dir, 'envelope.xml'), 'w')
fixup_namespaces(envelope)
f.write(envelope.xml(indent=u"yes"))
f.close()
for entry in doc.feed.entry:
    # fname = id_to_fname(unicode(entry.id))
    fname = make_entry_filename(entry)
    print fname
    f = open(os.path.join(output_dir, fname), 'w')
    f.write(entry.xml())
    f.close()


